package com.ioftv.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ioftv.common.Result;
import com.ioftv.dto.ImportResultDTO;
import com.ioftv.dto.LabelerBoxRecordExcelDTO;
import com.ioftv.dto.PageResult;
import com.ioftv.entity.LabelerBoxRecord;
import com.ioftv.listener.LabelerBoxRecordImportListener;
import com.ioftv.service.LabelerBoxRecordService;
import com.ioftv.util.UserContextUtil;
import com.ioftv.util.RolePermissionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 标注员拉框数实时看板Controller
 * 实现标注员拉框记录的增删改查、分页查询、Excel导入导出等功能
 */
@Slf4j
@RestController
@RequestMapping("/admin/labeler-box-count")
public class LabelerBoxRecordController {

    @Autowired
    private LabelerBoxRecordService labelerBoxRecordService;

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /**
     * 3.1 分页查询标注员拉框数列表
     * GET /admin/labeler-box-count
     */
    @GetMapping("/query")
    public Result<PageResult<LabelerBoxRecord>> getPageList(
            @RequestParam Integer currentPage,
            @RequestParam Integer pageSize,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @RequestParam(required = false) String labelerName,
            HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 创建分页对象
        Page<LabelerBoxRecord> page = new Page<>(currentPage, pageSize);
        
        // 构建查询条件
        LambdaQueryWrapper<LabelerBoxRecord> queryWrapper = new LambdaQueryWrapper<>();
        // 添加用户ID条件（管理员可查看所有数据）
        if (!RolePermissionUtil.isAdmin(role)) {
            queryWrapper.eq(LabelerBoxRecord::getUserId, userId);
        }
        if (startDate != null) {
            queryWrapper.ge(LabelerBoxRecord::getRecordDate, startDate);
        }
        if (endDate != null) {
            queryWrapper.le(LabelerBoxRecord::getRecordDate, endDate);
        }
        if (labelerName != null && !labelerName.trim().isEmpty()) {
            queryWrapper.like(LabelerBoxRecord::getLabelerName, labelerName);
        }
        queryWrapper.orderByDesc(LabelerBoxRecord::getSubmitTime);
        
        // 执行分页查询
        Page<LabelerBoxRecord> resultPage = labelerBoxRecordService.page(page, queryWrapper);
        
        // 构造返回结果
        PageResult<LabelerBoxRecord> pageResult = new PageResult<>(
            resultPage.getRecords(),
            resultPage.getTotal(),
            currentPage,
            pageSize
        );
        
        return Result.success(pageResult);
    }

    /**
     * 3.2 新增标注员拉框数记录
     * POST /admin/labeler-box-count
     */
    @PostMapping("/add")
    public Result<LabelerBoxRecord> addLabelerBoxRecord(@RequestBody LabelerBoxRecord labelerBoxRecord, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 设置用户ID
        labelerBoxRecord.setUserId(userId);
        
        // 参数校验
        if (labelerBoxRecord.getLabelerName() == null || labelerBoxRecord.getLabelerName().trim().isEmpty()) {
            return Result.error("标注员姓名不能为空");
        }
        
        if (labelerBoxRecord.getSubmitTime() == null) {
            return Result.error("提交时间不能为空");
        }
        
        if (labelerBoxRecord.getRecordDate() == null) {
            return Result.error("记录日期不能为空");
        }
        
        // 设置默认值
        if (labelerBoxRecord.getIsStandard() == null) {
            labelerBoxRecord.setIsStandard(0);
        }
        
        if (labelerBoxRecord.getTodayBoxCount() == null) {
            labelerBoxRecord.setTodayBoxCount(0);
        }
        
        if (labelerBoxRecord.getStandardValue() == null) {
            labelerBoxRecord.setStandardValue(0);
        }
        
        // 保存数据
        boolean success = labelerBoxRecordService.save(labelerBoxRecord);
        if (success) {
            return Result.success(labelerBoxRecord);
        } else {
            return Result.error("新增失败");
        }
    }

    /**
     * 3.3 修改标注员拉框数记录
     * PUT /admin/labeler-box-count/{id}
     */
    @PutMapping("/update/{id}")
    public Result<LabelerBoxRecord> updateLabelerBoxRecord(@PathVariable Long id, @RequestBody LabelerBoxRecord labelerBoxRecord, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 检查数据是否存在且属于当前用户
        LambdaQueryWrapper<LabelerBoxRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabelerBoxRecord::getId, id);
        // 添加用户ID条件（管理员可查看所有数据）
        if (!RolePermissionUtil.isAdmin(role)) {
            queryWrapper.eq(LabelerBoxRecord::getUserId, userId);
        }
        
        LabelerBoxRecord existing = labelerBoxRecordService.getOne(queryWrapper);
        if (existing == null) {
            return Result.error(404, "数据不存在或无权限访问");
        }
        
        // 设置ID
        labelerBoxRecord.setId(id);
        // 保持用户ID不变
        labelerBoxRecord.setUserId(existing.getUserId());
        
        // 更新数据
        boolean success = labelerBoxRecordService.updateById(labelerBoxRecord);
        if (success) {
            // 重新查询返回最新数据
            LabelerBoxRecord updated = labelerBoxRecordService.getOne(queryWrapper);
            return Result.success(updated);
        } else {
            return Result.error("修改失败");
        }
    }

    /**
     * 3.4 删除标注员拉框数记录
     * DELETE /admin/labeler-box-count/{id}
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteLabelerBoxRecord(@PathVariable Long id, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 检查数据是否存在且属于当前用户
        LambdaQueryWrapper<LabelerBoxRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabelerBoxRecord::getId, id);
        // 添加用户ID条件（管理员可查看所有数据）
        if (!RolePermissionUtil.isAdmin(role)) {
            queryWrapper.eq(LabelerBoxRecord::getUserId, userId);
        }
        
        LabelerBoxRecord existing = labelerBoxRecordService.getOne(queryWrapper);
        if (existing == null) {
            return Result.error(404, "数据不存在或无权限访问");
        }
        
        // 删除数据
        boolean success = labelerBoxRecordService.removeById(id);
        if (success) {
            return Result.success(null);
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 3.5 下载Excel导入模板
     * GET /admin/labeler-box-count/template
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("标注员拉框数导入模板", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 创建空模板（只有表头）
            List<LabelerBoxRecordExcelDTO> templateData = new ArrayList<>();

            // 写入Excel（只生成表头，不含数据）
            EasyExcel.write(response.getOutputStream(), LabelerBoxRecordExcelDTO.class)
                    .sheet("标注员拉框数数据")
                    .doWrite(templateData);

            log.info("下载Excel模板成功");
        } catch (IOException e) {
            log.error("下载Excel模板失败", e);
            throw new RuntimeException("下载模板失败: " + e.getMessage());
        }
    }

    /**
     * 3.6 批量导入Excel数据
     * POST /admin/labeler-box-count/import
     */
    @PostMapping("/import")
    public Result<ImportResultDTO> importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        if (file == null || file.isEmpty()) {
            return Result.error("请选择要导入的文件");
        }

        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
            return Result.error("仅支持Excel文件格式（.xlsx或.xls）");
        }

        try {
            log.info("开始导入Excel文件: {}", fileName);

            // 创建导入结果对象
            ImportResultDTO importResult = new ImportResultDTO();

            // 使用监听器模式读取Excel，支持大文件
            LabelerBoxRecordImportListener listener = new LabelerBoxRecordImportListener(labelerBoxRecordService, importResult);
            listener.setUserId(userId); // 设置用户ID用于数据隔离
            
            EasyExcel.read(file.getInputStream(), 
                          LabelerBoxRecordExcelDTO.class, 
                          listener)
                    .sheet()
                    .doRead();

            log.info("导入完成: 总行数={}, 成功={}, 失败={}", 
                    importResult.getTotalRows(), 
                    importResult.getSuccessRows(), 
                    importResult.getFailRows());

            return Result.success(importResult);

        } catch (IOException e) {
            log.error("导入Excel文件失败", e);
            return Result.error("导入失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("导入Excel文件异常", e);
            return Result.error("导入异常: " + e.getMessage());
        }
    }
}